package TG_350;

import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class Solution {
	public int[] intersect(int[] nums1, int[] nums2) {
		Map<Integer, Integer> nums1hash = new HashMap<Integer, Integer>();
		Map<Integer, Integer> nums2hash = new HashMap<Integer, Integer>();
		for (int num : nums1) {
			nums1hash.put(num, nums1hash.getOrDefault(num, 0) + 1);
		}
		for (int num : nums2) {
			nums2hash.put(num, nums2hash.getOrDefault(num, 0) + 1);
		}
		Set<Integer> nums1Set = nums1hash.keySet();
		Set<Integer> nums2Set = nums2hash.keySet();

		Set<Integer> eleSet = new HashSet<Integer>();
		if (nums1Set.size() > nums2Set.size()) {
			eleSet = nums1Set;
		} else {
			eleSet = nums2Set;
		}
		List<Integer> resList=new LinkedList<Integer>();
		for (Integer ele : eleSet) {
			int nums1Count= nums1hash.getOrDefault(ele, 0);
			int nums2Count= nums2hash.getOrDefault(ele, 0);
			int minCount = Math.min(nums1Count, nums2Count);
			if (minCount==0) {
				continue;
			}else {
				while (minCount>0) {
					resList.add(ele);
					minCount--;
				}
			}
		}
		int[] res=new int[resList.size()];
		for (int i = 0; i < resList.size(); i++) {
			res[i]=resList.get(i);
		}
		
		
		return res;

	}
}
